对于`Promise`部分属性的理解
对于Promise
部分属性的理解
对于Promise.then()
和Promise.catch()
的理解
今天碰到问题是这样子的:
调试bug的时候发现axios走了then也走了有catch,在我印象里是走了then就不该走catch(后来发现是我理解错了)
代码是这样的1
2
3
4
5
6
7
8
9this.axios.post('/user/login', params)
.then(res => {
console.log('response', res)
})
.catch(err => {
// 这个catch catch的是then里的异常,then里如果有任何异常都会被catch捕获
console.log('catch')
console.error(err.message)
})
仔细看了Promise.catch()
MCDN是这样解释的
The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling Promise.prototype.then(undefined, onRejected) (in fact, calling obj.catch(onRejected) internally calls obj.then(undefined, onRejected)).
简单来讲调用Promise.catch()
等于调用Promise.prototype.then(undefined, onRejected)
由于Promise.then()
返回的是一个Promise
对象,返回值解释如下:
throws an error, the promise returned by then gets rejected with the thrown error as its value;
如果抛出异常返回一个执行rejected
的Promise
对象即相当于调用返回Promise
的Promise.then(undefined, onRejected)
对于Promise.catch()
的返回值是这样解释的:
The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is resolved.
如果Promise.catch()
又抛出异常则相当于又调用Promise.then(undefined, onRejected)
如果未抛出异常则相当于调用Promise.then(onResolved,undefined)
promise.all()是顺序开始,异步执行,顺序返回
1 | // 示例代码 |
详见这里